from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer
from . import models


def generate_email_url_token(user):
    """加密用户信息"""
    # 1.准备数据
    user_data = {'user_id': user.id, 'user_email': user.email}
    # 2. 创建TJSWSerializer对象
    serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=60 * 30)
    # 3. 生成加密
    token = serializer.dumps(user_data)
    # 4.拼接加密url
    verify_url = '{}?token={}'.format(settings.EMAIL_VERIFY_URL, token.decode())

    return verify_url


def check_verify_email_token(token):
    """解密用户信息"""
    try:
        serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=60 * 30)
        dict_data = serializer.loads(token)
        # 数据库查找数据
        user = models.User.objects.get(id=dict_data['user_id'])
    except Exception:
        return None
    return user
